from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QMainWindow, QAction, QStatusBar,
                             QMessageBox, QTabWidget, QMdiArea, QMdiSubWindow)
from PyQt5.QtCore import Qt

from common.file_compare import FileCompareWidget
from common.notepad import NotepadWidget
from config import GLOBAL_STATE, update_state, get_state


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mdi_area = None
        self.file_compare_windows = []
        self.notepad_windows = []
        self.init_ui()
        self.setWindowIcon(QIcon('tool.ico'))  # 设置窗口图标

    def init_ui(self):
        """初始化主界面"""
        app_name = GLOBAL_STATE.get('app_name','多功能工具框架')
        self.setWindowTitle(app_name)
        # self.showMaximized()

        # 使用QMdiArea实现多文档界面
        self.mdi_area = QMdiArea()
        self.mdi_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.mdi_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setCentralWidget(self.mdi_area)

        self.create_menubar()
        # self.create_statusbar()
        # update_state('main_window.created', True)

    def create_menubar(self):
        """创建菜单栏"""
        menubar = self.menuBar()

        # 文件菜单
        file_menu = menubar.addMenu('文件(&F)')

        # 比较工具
        compare_action = QAction('文件比较', self)
        compare_action.setStatusTip('打开文件比较工具')
        compare_action.triggered.connect(self.show_file_compare)
        file_menu.addAction(compare_action)

        # 记事本编辑
        notepad_action = QAction('记事本编辑', self)
        notepad_action.setStatusTip('打开记事本编辑工具')
        notepad_action.triggered.connect(self.show_notepad_editor)
        file_menu.addAction(notepad_action)

        file_menu.addSeparator()

        # 退出动作
        exit_action = QAction('退出(&X)', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.setStatusTip('退出应用程序')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # 窗口菜单
        window_menu = menubar.addMenu('窗口(&W)')

        cascade_action = QAction('级联窗口(&C)', self)
        cascade_action.triggered.connect(self.mdi_area.cascadeSubWindows)
        window_menu.addAction(cascade_action)

        tile_action = QAction('平铺窗口(&T)', self)
        tile_action.triggered.connect(self.mdi_area.tileSubWindows)
        window_menu.addAction(tile_action)

        window_menu.addSeparator()

        close_all_action = QAction('关闭所有(&A)', self)
        close_all_action.triggered.connect(self.close_all_windows)
        window_menu.addAction(close_all_action)

        # 帮助菜单
        help_menu = menubar.addMenu('帮助(&H)')
        about_action = QAction('关于(&A)', self)
        about_action.setStatusTip('显示程序信息')
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

    def create_statusbar(self):
        """创建状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage('就绪', 5000)

    def show_file_compare(self):
        """显示文件比较工具"""
        sub_window = QMdiSubWindow()
        compare_widget = FileCompareWidget()
        sub_window.setWidget(compare_widget)
        sub_window.setWindowTitle(f"文件比较 {len(self.file_compare_windows) + 1}")
        sub_window.resize(800, 600)

        self.mdi_area.addSubWindow(sub_window)
        sub_window.show()
        sub_window.showMaximized()

        self.file_compare_windows.append(sub_window)
        # self.status_bar.showMessage('已打开文件比较工具', 3000)

    def show_notepad_editor(self):
        """显示记事本编辑工具"""
        sub_window = QMdiSubWindow()
        notepad_widget = NotepadWidget()

        # 关键修正：将QMdiSubWindow引用传递给NotepadWidget
        notepad_widget.set_mdi_window(sub_window)

        sub_window.setWidget(notepad_widget)
        sub_window.setWindowTitle(f"记事本编辑器 {len(self.notepad_windows) + 1}")
        sub_window.resize(600, 500)

        self.mdi_area.addSubWindow(sub_window)
        sub_window.show()

        self.notepad_windows.append(sub_window)
        # self.status_bar.showMessage('已打开记事本编辑工具', 3000)

    def close_all_windows(self):
        """关闭所有子窗口"""
        self.mdi_area.closeAllSubWindows()
        self.file_compare_windows.clear()
        self.notepad_windows.clear()
        # self.status_bar.showMessage('已关闭所有窗口', 3000)

    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于",
                          f"{GLOBAL_STATE['app_name']}\n"
                          f"版本 {GLOBAL_STATE['version']}\n\n"
                          "包含多种实用工具")

    def closeEvent(self, event):
        """重写关闭事件"""
        # update_state('last_window_size', (self.width(), self.height()))

        # 检查是否有未保存的记事本
        for notepad_window in self.notepad_windows:
            notepad_widget = notepad_window.widget()
            if hasattr(notepad_widget, 'is_modified') and notepad_widget.is_modified():
                reply = QMessageBox.question(
                    self, '保存修改',
                    '有未保存的文档，要保存吗？',
                    QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                    QMessageBox.Cancel
                )
                if reply == QMessageBox.Cancel:
                    event.ignore()
                    return
                elif reply == QMessageBox.Yes:
                    notepad_widget.save_file()

        event.accept()